from ..models.sources_model import Sources
from sqlalchemy.orm import Session
from sqlalchemy import select
from fastapi import HTTPException


def get_all_sources(db: Session):
    query = select(Sources).order_by(Sources.id.asc())
    sources = db.execute(query).scalars().all()
    return [source.as_dict() for source in sources]


def create_source(db: Session, source_data):
    if db.execute(select(Sources).where(Sources.name == source_data.name)).scalars().first():
        raise HTTPException(status_code=400, detail=f"Source {source_data.name} already exists")
    new_source = Sources(**source_data.model_dump())
    db.add(new_source)
    db.commit()
    db.refresh(new_source)
    return new_source


def update_source(db: Session, source_id, source_data):
    exist_source = db.execute(select(Sources).where(Sources.id == source_id)).scalar()
    if not exist_source:
        raise HTTPException(status_code=404, detail=f"Source {source_id} not found")
    for k, v in source_data.model_dump().items():
        setattr(exist_source, k, v)
    db.commit()
    return exist_source


def delete_source(db: Session, source_id):
    exist_source = db.get(Sources, source_id)
    if not exist_source:
        raise HTTPException(status_code=404, detail="Source not found")
    db.delete(exist_source)
    db.commit()
    return exist_source


def check_source_exists(db: Session, source_id):
    return db.get(Sources, source_id) is not None

def get_source_by_name(db: Session, name):
    source = db.execute(select(Sources).where(Sources.name == name)).scalar()
    return source.as_dict()



# if __name__ == "__main__":
#     from database.db import SessionLocal
#     db = SessionLocal()
#     print(get_source_by_name(db,"textbook"))